//buy.wxml
const app = getApp();
var level = require('../../utils/level.js');//导入等级数据列表
var config = require('../../utils/parts.js');
var header = getApp().request("header");
var requestUrl = getApp().request("url");
Page({
    data: {
        userInfo: {},
        animation: '',
        goldcoin: 0,//用户金币数量
        bao: 15200,//用户大通宝数量
        carType: 1,//选车当前车型
        carName: '',//当前车型名字
        buyCarShow: false,//购车弹窗
        getCoinShow: false,//获取金币弹窗        
        getBaoShow: false,//获取大通宝弹窗
        coin2bao: false,//大通宝兑换金币弹窗
        coin2baoItem: 0,//金币兑换大通宝选中条目 
        levelItem: level.list,//等级信息列表               
        buyCarSuccess: false,//购车成功弹窗
        introOpen: 'close',//车辆介绍
        carName: 'SUV概念车',//车名
        baseRequestUrl:config.apiUrl,//线上接口地址        
        baseImgUrl: config.imgUrl,//图片地址
        buy_car_switch: true,//防止买车二次点击  
        score: 0 ,//用户总分
        close_success:false,
        success_gold:"1000",
        dtbArr: [5, 25, 50, 250]
    },
    onLoad: function (options) {
      console.log(app.globalData);
        // 生命周期函数--监听页面加载
        var _this = this;
        //获取用户信息
        var nickName = app.globalData.nickName,
            avatarUrl = app.globalData.avatarUrl,
            goldcoin = app.globalData.gold,
            userId = app.globalData.session_key.userId,
            salt = app.globalData.session_key.salt;
        console.log(app.globalData.userId);
        var userInfo = {
            nickName: nickName,
            avatarUrl: avatarUrl
        }
        this.setData({
            userInfo: userInfo,
            goldcoin: goldcoin,
            userId: userId,
            salt: salt
        })
    },
    onShow:function(){
      wx.showShareMenu({
        withShareTicket: true
      });
    },
    onShareAppMessage:function(){
      //是否选车
      var fightCarTypeId = app.globalData.fightCarTypeId;
      //随机一句宣言
      var declaration = getApp().Refit();
      var storageRefit = app.globalData.myRefitTxt;
      var myRefitTxt = declaration.indexOf(storageRefit);
      console.log(myRefitTxt)
      if (fightCarTypeId == 0) {
        return {
          title: getApp().shareTitle1(),
          path: "/pages/index/index"
        }
      } else {
        return {
          title: getApp().shareTitle2(),
          path: "/pages/openShare/openShare?shareId=" + app.globalData.session_key.userId + "&carTypeId=" + fightCarTypeId + "&shareRefitNum=" + myRefitTxt + "&carName=SUV概念车",
          success: (re) => {
            if (Object.keys(re).length == 1) {
              return
            }
            var ticket = re.shareTickets[0];
            getApp().shareFn(ticket);
          }
        }
      }
    },
    onReady: function () {
        // 页面渲染完成
        //实例化一个动画
        this.animation = wx.createAnimation({
            // 动画持续时间，单位ms，默认值 400
            duration: 3000,
            /**
             * http://cubic-bezier.com/#0,0,.58,1  
             *  linear  动画一直较为均匀
             *  ease    从匀速到加速在到匀速
             *  ease-in 缓慢到匀速
             *  ease-in-out 从缓慢到匀速再到缓慢
             * 
             *  http://www.tuicool.com/articles/neqMVr
             *  step-start 动画一开始就跳到 100% 直到动画持续时间结束 一闪而过
             *  step-end   保持 0% 的样式直到动画持续时间结束        一闪而过
             */
            timingFunction: 'linear',
            // 延迟多长时间开始
            delay: 100,
            /**
             * 以什么为基点做动画  效果自己演示
             * left,center right是水平方向取值，对应的百分值为left=0%;center=50%;right=100%
             * top center bottom是垂直方向的取值，其中top=0%;center=50%;bottom=100%
             */
            transformOrigin: '86% 56%'
        })
    },
    //立即兑换大通宝按钮
    btnNowExchange() {
      var that = this;
      //未选中金币不能兑换
      if (this.data.coin2baoItem == 0) { return }
      var dtbArr = this.data.dtbArr;     //大通宝数组
      var dtbItem = this.data.coin2baoItem - 1;  //选中的哪个大通宝
      var dtbNum = dtbArr[dtbItem];              //选中的大通宝数量
      //请求大通宝和是否登录
      wx.showLoading({
        title: '',
        mask:true
      })
      wx.request({
        url: requestUrl + 'baoExchangeGold',
        method: "POST",
        data: { userId: app.globalData.session_key.userId, salt: app.globalData.session_key.salt, bao: dtbNum },
        header: header,
        success: (res) => {
          console.log(res);
          if (res.statusCode != 200) {
            getApp().showModal("服务器异常");
            return
          }
          wx.hideLoading();
          if (res.data.code == 200) {
            //data大金币数量增加
            var goldcoin = this.data.goldcoin;
            goldcoin += dtbNum * 200;
            //本地存储的金币相应增加
            app.globalData.gold = goldcoin;
            that.setData({
              coin2bao: false,   //关闭窗口
              coin2baoItem: 0,    //大通宝选项初始化
              goldcoin: goldcoin,  //金币数量
              success_gold: dtbNum * 200,
              close_success: true
            });

          } else if (res.data.code == 402) {
            getApp().showModal("提交大通宝数量有误！");
          } else if (res.data.code == 401 || res.data.code == 301 || res.data.code == 302) {
            getApp().showModal("系统信息有误，请重试！");
          } else if (res.data.code == 304) {
            getApp().showModal("大通宝余额不足！");
          } else if (res.data.code == 305) {
            getApp().showModal("大通宝余额不足！");
          } else if (res.data.code == 306) {
            getApp().showModal("大通宝兑换金币失败，请重试！");
          } else if (res.data.code == 303) {
            wx.navigateTo({
              url: '../login/login?url=index'
            })
          } else if (res.data.code == 800) {
            getApp().showModal(res.data.data.msg);
            wx.hideLoading();
          }
          
        },
        fail:function(res){
          console.log("大通宝接口fail");
          console.log(res);
          wx.hideLoading();
          app.showModal("网络超时，请检查您的网络");
        }
      });
    },
    rotate: function () {
        this.animation.rotate(360).step()
        this.setData({
            //输出动画
            animation: this.animation.export()
        })
    },
    toStorePage: function () {
        wx.navigateTo({
            url: '../store/store'
        })
    },
    //关闭按钮处理
    closeView: function (event) {
        var name = event.target.dataset.name;
        this.setData({
            [name]: false
        })
        if (event.target.id === 'intro') {
            wx.setStorage({
                key: 'intro',
                data: true
            })
        }
    },
    //打开按钮处理
    openView: function (event) {
        var name = event.target.dataset.name;
        this.setData({
            [name]: true
        })
    },
    //打开金币兑换大通宝页面
    tocoin2bao: function () {
        this.setData({
            getCoinShow: false,
            coin2bao: true
        });
        // wx.showToast({
        //     title:'敬请期待',
        //     icon:'none'
        //   })
    },
    toWarehousePage(){
        //前往仓库页面
        this.setData({
            getCoinShow:false
          })
        wx.navigateTo({
            url:'../warehouse/warehouse'
        })
    },
    //金币兑换大通宝选项逻辑
    coin2bao: function (event) {
        var num = event.target.dataset.num;
        if (this.data.coin2baoItem == num) {
            this.setData({
                coin2baoItem: 0
            })
        } else {
            this.setData({
                coin2baoItem: num
            })
        }
    },
    choseCar: function (event) {
        //切换选车组件
        var car_type = event.target.dataset.type,
            car_name_arr = ['SUV概念车', '越野一族', '商务座驾'],
            car_name = car_name_arr[car_type - 1];

        this.setData({
            carType: car_type,
            carName: car_name
        })
    },
    buyCar: function () {
        //点击金币购车

        this.setData({
            buyCarShow: true
        })
    },
    introHandler: function (event) {
        //车辆介绍弹窗
        if (this.data.introOpen === 'open') {
            this.setData({
                introOpen: 'close'
            })
        } else {
            this.setData({
                introOpen: 'open'
            })
        }
    },
    buyCarHandler: function () {
        //点击确定购车
        var _this = this;
        var user_car = this.data.carType,//获取到用户选择的车型
          user_gold = this.data.goldcoin;//获取用户金币
        if (user_gold < 5000) {
          wx.showToast({
            title: '您的金币不足',
            icon: 'none'
          })
        } else {
          wx.showLoading({
            title: ' ',
            mask: true
          });
          wx.request({
            url: _this.data.baseRequestUrl + 'buyNewCar',
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            data: {
              userId: app.globalData.session_key.userId,
              salt: app.globalData.session_key.salt,
              carTypeId: 1
            },
            success: function (res) {
              console.log(res);
              if (res.statusCode != 200) {
                getApp().showModal("服务器异常");
                return
              }
              wx.hideLoading();
              if (res.data.code == 200) {
                var lastGold = _this.data.goldcoin - 5000,
                  newScore = _this.data.score + 5000,
                  carName = _this.data.carType,
                  car = app.globalData.car;
                car[0].type = 1;
                var ar = ['SUV概念车', '越野一族', '商务座驾'];
                app.globalData.gold= lastGold;
                app.globalData.fightCarTypeId= 1;
                app.globalData.score=newScore;
                app.globalData.carName=carName;
                app.globalData.car= car;
                app.globalData.car_name=ar[carName - 1];
                _this.setData({
                  goldcoin: lastGold,
                  buyCarShow: false,
                  buyCarSuccess: true,
                  score: newScore,
                  buy_car_switch: true
                })
                wx.hideLoading();
              }else if(res.data.code==201){
                wx.showToast({
                  title:"已购买该型号车辆，不能重复购买",
                  icon:"none",
                  duration:2000
                });
              }else if(res.data.code==401){
                wx.showToast({
                  title: "空值",
                  icon: "none",
                  duration: 2000
                });
              }else if(res.data.code==402){
                wx.showToast({
                  title: "carTypeId错误",
                  icon: "none",
                  duration: 2000
                });
              }else if(res.data.code==301){
                wx.showToast({
                  title: "userId错误",
                  icon: "none",
                  duration: 2000
                });
              }else if(res.data.code==302){
                wx.showToast({
                  title: "salt错误",
                  icon: "none",
                  duration: 2000
                });
              }else if(res.data.code==303){
                wx.showToast({
                  title: "金币不足",
                  icon: "none",
                  duration: 2000
                });
              } else if (res.data.code == 800) {
                getApp().showModal(res.data.data.msg);
                wx.hideLoading();
              }
            },
            fail:function(){
              console.log("购车接口失败fail")
              wx.hideLoading();
              getApp().showModal("网络超时，请检查您的网络");
            }
          })
        }
        
    },
    setStorage: function (name, data) {
        //设置本地存储
        wx.setStorage({
            key: name,
            data: data,
            success: function () {
                console.log("%c存储用户" + name + "成功", 'background:#017b40;color:#fff');
            },
            fail: function (res) {
                console.log('%c存储用户' + name + '失败!\n' + res, 'background:rgba(0,0,0,0.1);color:red');
            }
        })
    },
    back: function () {
        //返回上一页
      wx.redirectTo({
        url: '../index/index'
        })
    }
})